package com.cqq.normal.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cqq.common.core.base.BaseService;
import com.cqq.common.core.constant.CommonMessage;
import com.cqq.common.core.util.BeanUtil;
import com.cqq.normal.dao.ConstantDao;
import com.cqq.normal.dao.domain.Constant;
import com.cqq.normal.service.ConstantService;
import com.cqq.normal.service.bean.ConstantBean;
import com.cqq.normal.service.exception.ConstantServiceException;

@Service("constantService")
public class ConstantServiceImpl extends BaseService implements ConstantService {

	@Autowired
	ConstantDao constantDao;

	
	public Integer addConstant(ConstantBean constantBean) throws ConstantServiceException {

		if (constantBean.getId() != null) {
			throw super.buildException(new ConstantServiceException(CommonMessage.COMMON_PARAM_ERROR));
		}
		
		if(StringUtils.isBlank(constantBean.getName()) || StringUtils.isBlank(constantBean.getType()) || StringUtils.isBlank(constantBean.getValue())
				|| constantBean.getIndex() == null){
			throw super.buildException(new ConstantServiceException(CommonMessage.COMMON_PARAM_EMPTY));
		}

		Constant constant = BeanUtil.copy(constantBean, Constant.class);
		constantDao.add(constant);
		return constant.getId();
	}

	
	public boolean deleteConstant(Integer id) throws ConstantServiceException {
		if (id == null) {
			throw super.buildException(new ConstantServiceException(CommonMessage.COMMON_PARAM_ERROR));
		}
		
		int size = constantDao.delete(id);
		if(size < 1){
			return false;
		}
		
		return true;
	}

	
	public boolean updateConstant(ConstantBean constantBean) throws ConstantServiceException {
		if(constantBean.getId() == null){
			throw super.buildException(new ConstantServiceException(CommonMessage.COMMON_PARAM_ERROR));
		}
		
		Constant constant = BeanUtil.copy(constantBean, Constant.class);
		
		int size = constantDao.update(constant);
		if(size < 1){
			return false;
		}
		return true;
	}

	
	public List<ConstantBean> listConstantByType(String type) throws ConstantServiceException {
		if(StringUtils.isBlank(type)){
			throw super.buildException(new ConstantServiceException(CommonMessage.COMMON_PARAM_ERROR));
		}
		
		List<Constant> constants = constantDao.queryByType(type);
		
		List<ConstantBean> result = BeanUtil.copyList(constants, ConstantBean.class);
		return result;
	}

	
	public List<ConstantBean> listAllConstant() {
		return BeanUtil.copyList(constantDao.queryAll(), ConstantBean.class);
	}

}
